package com.mashibing.test.singleton;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author: mayu
 * @date: 2021年05月18日 16:36
 * 懒汉式
 * synchronized 2
 */
public class S4 {
    private static S4 INSTANCE = null;

    private S4() {
    }

    public static S4 getInstance() {
        if (INSTANCE == null) {

            //此处会有多个线程进来,new多次,得到多个实例

            synchronized (S4.class) {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                INSTANCE = new S4();
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        CountDownLatch cdl = new CountDownLatch(1000);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "：" + S4.getInstance().hashCode());
                cdl.countDown();
            }).start();
        }

        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("执行耗时：" + (end - start));//71033
    }
}
